package com.shenyue.nbtownlet.activity;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.SearchView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.adapter.LabelListViewAdapter;
import com.shenyue.nbtownlet.adapter.SpecialMeasuresListViewAdapter;
import com.shenyue.nbtownlet.base.BaseActivity;
import com.shenyue.nbtownlet.databinding.ActivitySpecialMeasuresBinding;
import com.shenyue.nbtownlet.databinding.AreaViewBinding;
import com.shenyue.nbtownlet.event.BaseListener;
import com.shenyue.nbtownlet.model.AppContactsModel;
import com.shenyue.nbtownlet.model.AppDissertationModel;
import com.shenyue.nbtownlet.model.AppLoginModel;
import com.shenyue.nbtownlet.model.AppModel;
import com.shenyue.nbtownlet.model.DefaultModel;
import com.shenyue.nbtownlet.util.NetWorkUtils;
import com.shenyue.nbtownlet.util.StringUtil;

/**
 * 专项整治
 */
public class SpecialMeasuresActivity extends BaseActivity implements SpecialMeasuresListViewAdapter.SpecialMeasuresListItemClickListener, View.OnClickListener, AdapterView.OnItemClickListener {
    private ActivitySpecialMeasuresBinding binding;
    private Context mContext;
    private SpecialMeasuresListViewAdapter listViewAdapter;
    private int pageNo = 1, pageSize = 10;
    private Handler mHandler = new Handler();
    private MenuItem searchMenu;
    private SearchView searchView;
    private AreaViewBinding areaViewBinding;
    private BottomSheetDialog areaSheetDialog;
    private LabelListViewAdapter countyListViewAdapter, streetListViewAdapter;
    private boolean isAreaLoading = false;
    private String townType = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_special_measures);
        setActionBar(true, getString(R.string.tv_special_measures));
        mContext = this;

        listViewAdapter = new SpecialMeasuresListViewAdapter(mContext);
        binding.listView.setAdapter(listViewAdapter);
        listViewAdapter.setOnItemClickListener(this);

        binding.ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if (!NetWorkUtils.isNetworkConnected(mContext)) {
                    binding.ptrClassicFrameLayout.refreshComplete();
                    showMsg(getString(R.string.no_network));
                    return;
                }
                query();
            }
        });

        binding.ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                if (!NetWorkUtils.isNetworkConnected(mContext)) {
                    binding.ptrClassicFrameLayout.loadMoreComplete(false);
                    showMsg(getString(R.string.no_network));
                    return;
                }
                queryMore();
            }
        });
        binding.ptrClassicFrameLayout.disableWhenHorizontalMove(true);

        setArea();

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                binding.ptrClassicFrameLayout.autoRefresh();
            }
        }, 32);
    }

    private void setArea() {
        areaViewBinding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.area_view, null, false);
        areaSheetDialog = new BottomSheetDialog(this);
        areaSheetDialog.setContentView(areaViewBinding.getRoot());
        areaSheetDialog.setCancelable(false);
        areaSheetDialog.setCanceledOnTouchOutside(false);
        areaViewBinding.btnOk.setOnClickListener(this);
        areaViewBinding.btnCancel.setOnClickListener(this);
        countyListViewAdapter = new LabelListViewAdapter(mContext);
        areaViewBinding.county.setAdapter(countyListViewAdapter);
        areaViewBinding.county.setOnItemClickListener(this);

        streetListViewAdapter = new LabelListViewAdapter(mContext);
        areaViewBinding.street.setAdapter(streetListViewAdapter);
        areaViewBinding.street.setOnItemClickListener(this);
    }

    private void query() {
        listViewAdapter.clear();
        pageNo = 1;
        JSONObject param = new JSONObject();
        param.put("name", searchView == null ? "" : searchView.getQuery().toString());
        param.put("townType", townType);
        param.put("pageIndex", pageNo);
        param.put("pageSize", pageSize);
        AppDissertationModel.GetPointList(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                binding.ptrClassicFrameLayout.refreshComplete();
                JSONObject data = JSON.parseObject(val);
                JSONArray array = data.getJSONArray("Data");
                long count = array.size();
                binding.ptrClassicFrameLayout.setLoadMoreEnable(!(count < pageSize));
                listViewAdapter.addItems(array);
            }

            @Override
            public void error(String error, String action) {
                binding.ptrClassicFrameLayout.refreshComplete();
                showMsg(error);
            }
        });
    }

    private void queryMore() {
        pageNo += 1;
        JSONObject param = new JSONObject();
        param.put("name", searchView == null ? "" : searchView.getQuery().toString());
        param.put("townType", townType);
        param.put("pageIndex", pageNo);
        param.put("pageSize", pageSize);
        AppDissertationModel.GetPointList(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                JSONObject data = JSON.parseObject(val);
                JSONArray array = data.getJSONArray("Data");
                binding.ptrClassicFrameLayout.loadMoreComplete(!(array.size() < pageSize));
                listViewAdapter.addItems(array);
            }

            @Override
            public void error(String error, String action) {
                binding.ptrClassicFrameLayout.loadMoreComplete(false);
                showMsg(error);
            }
        });
    }

    private void setSearchView() {
        if (this.searchView != null) {
            EditText searchPlate = (EditText) this.searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
            if (searchPlate == null)
                return;
            searchPlate.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        binding.ptrClassicFrameLayout.autoRefresh();
                    }
                    return false;
                }
            });
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.special_measures_menu, menu);
        searchMenu = menu.findItem(R.id.action_search);
        searchView = (SearchView) searchMenu.getActionView();
        searchView.setQueryHint("请输入名称检索");
        setSearchView();
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        hideSearchView();
        switch (item.getItemId()) {
            case R.id.action_menu:
                areaSheetDialog.show();
                if (isAreaLoading)
                    break;
                queryCountyList();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void hideSearchView() {
        if (this.searchMenu != null)
            this.searchMenu.collapseActionView();
    }

    @Override
    public void onItemClick(int position) {
        if (!NetWorkUtils.isNetworkConnected(this)) {
            showMsg(getString(R.string.no_network));
            return;
        }
        JSONObject item = (JSONObject) listViewAdapter.getItem(position);
        Bundle bundle = new Bundle();
        bundle.putString(DefaultModel.PAGE_DATA, item.toString());
        toActivity(SpecialMeasuresDetailActivity.class, bundle);
    }

    private void setAreaId() {
        JSONArray countyList = countyListViewAdapter.getItems();
        for (int i = 0, j = countyList.size(); i < j; i++) {
            JSONObject item = (JSONObject) countyList.get(i);
            if (item.getBooleanValue("selected"))
                townType = StringUtil.dTs(item.getString("ID"));
        }
        JSONArray streetList = streetListViewAdapter.getItems();
        for (int i = 0, j = streetList.size(); i < j; i++) {
            JSONObject item = (JSONObject) streetList.get(i);
            if (item.getBooleanValue("selected"))
                townType = StringUtil.dTs(item.getString("ID"));
        }
    }

    private void queryCountyList() {
        JSONObject param = new JSONObject();
        param.put("areaid", AppModel.getNingBoAreaID(mContext));
        param.put("areaidByIdentity", AppLoginModel.getAreaId(mContext));
        AppContactsModel.GetNextLevelAreaID(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                isAreaLoading = true;
                countyListViewAdapter.clear();
                countyListViewAdapter.addItems(JSON.parseArray(val));
            }

            @Override
            public void error(String error, String action) {

            }
        });
    }

    private void queryStreetList(String areaid) {
        JSONObject param = new JSONObject();
        param.put("areaid", areaid);
        param.put("areaidByIdentity", AppLoginModel.getAreaId(mContext));
        AppContactsModel.GetNextLevelAreaID(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                streetListViewAdapter.clear();
                streetListViewAdapter.addItems(JSON.parseArray(val));
            }

            @Override
            public void error(String error, String action) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_cancel:
                areaSheetDialog.hide();
                break;
            case R.id.btn_ok: {
                areaSheetDialog.hide();
                setAreaId();
                binding.ptrClassicFrameLayout.autoRefresh();
                break;
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent == areaViewBinding.county) {
            JSONArray countyList = countyListViewAdapter.getItems();
            for (int i = 0, j = countyList.size(); i < j; i++) {
                JSONObject item = (JSONObject) countyList.get(i);
                item.put("selected", false);
            }
            JSONObject item = (JSONObject) countyList.get(position);
            item.put("selected", true);
            countyListViewAdapter.notifyDataSetChanged();
            queryStreetList(StringUtil.dTs(item.getString("ID")));
        } else if (parent == areaViewBinding.street) {
            JSONArray streetList = streetListViewAdapter.getItems();
            for (int i = 0, j = streetList.size(); i < j; i++) {
                JSONObject item = (JSONObject) streetList.get(i);
                item.put("selected", false);
            }
            JSONObject item = (JSONObject) streetList.get(position);
            item.put("selected", true);
            streetListViewAdapter.notifyDataSetChanged();
        }
    }
}
